package com.daikuan.fffkuaiban.ui.fragment;

import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.daikuan.fffkuaiban.adapter.HomeGridViewAdapter;
import com.daikuan.fffkuaiban.adapter.HomeListAdapter;
import com.daikuan.fffkuaiban.adapter.HomeListAdapter2;
import com.daikuan.fffkuaiban.bmobBean.ButtonConfigBean;
import com.daikuan.fffkuaiban.bmobBean.ClickBean;
import com.daikuan.fffkuaiban.ui.activity.QiangqianActivity;
import com.daikuan.fffkuaiban.ui.activity.YouXuanActivity;
import com.daikuan.fffkuaiban.widget.MyGridView;
import com.jarhead.common.base.BaseFragment;
import com.jarhead.common.commonutils.ToastHelper;
import com.lcodecore.tkrefreshlayout.Footer.LoadingView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.daikuan.fffkuaiban.R;
import com.daikuan.fffkuaiban.adapter.YouxuanDaikuanListAdapter;
import com.daikuan.fffkuaiban.bmobBean.BannerBean;
import com.daikuan.fffkuaiban.bmobBean.ListConfig;
import com.daikuan.fffkuaiban.bmobBean.TypeInfo;
import com.daikuan.fffkuaiban.ui.activity.WebViewActivity;
import com.daikuan.fffkuaiban.utils.AdViewpagerUtil;
import com.daikuan.fffkuaiban.widget.ScrollViewWithListView;
import com.sunfusheng.marqueeview.MarqueeView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;

/**
 * Created by jiming1 on 2017/6/30.
 */
public class HomeFragment extends BaseFragment {


	@Bind(R.id.listView)
	ScrollViewWithListView scrollViewWithListView;
	@Bind(R.id.refresh)
	TwinklingRefreshLayout refreshLayout;
	@Bind(R.id.gridView_8)
	MyGridView gridView_8;
	@Bind(R.id.marqueeView)
	MarqueeView marqueeView;
	HomeGridViewAdapter homeGridViewAdapter;
	LayoutInflater layoutInflater;
	List<ListConfig> listConfigs;
	List<ButtonConfigBean> buttonConfigBeens;
	HomeListAdapter2 adapter;
	int count = 0;
	@Bind(R.id.tvEdu)
	TextView tvEdu;

	private int edu[] = {50000, 55000, 60000, 65000, 70000, 75000, 80000, 66000, 61000, 58000, 78000, 77000, 63000, 56000};

	@Override
	protected int getLayoutResource() {
		return R.layout.fragment_home;
	}

	@Override
	public void initPresenter() {

	}

	@Override
	protected void initView() {

		int random = new Random().nextInt(edu.length - 1);
		int money = edu[random];
		tvEdu.setText(money + "");

		layoutInflater = LayoutInflater.from(getActivity());
		SinaRefreshView headerView = new SinaRefreshView(getActivity());
		headerView.setArrowResource(R.mipmap.arrow);
		headerView.setTextColor(0xff745D5C);
		refreshLayout.setHeaderView(headerView);
		LoadingView loadingView = new LoadingView(getActivity());
		refreshLayout.setBottomView(loadingView);
		refreshLayout.setEnableLoadmore(true);


		gridView_8.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ButtonConfigBean buttonConfigBean = homeGridViewAdapter.getItem(position);
				if (buttonConfigBean == null)
					return;
				YouXuanActivity.jump(buttonConfigBean.type_id, buttonConfigBean.type_name, getActivity());

			}
		});

		refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
			@Override
			public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
				count = 0;
				getButtonConfig();
				getList(false);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						refreshLayout.finishRefreshing();
					}
				}, 2000);
			}

			@Override
			public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
				super.onLoadMore(refreshLayout);
				count++;
				getList(true);
			}
		});

		scrollViewWithListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				ListConfig listConfig = adapter.getItem(i);
				WebViewActivity.skip(getActivity(), listConfig.channel_gourl, listConfig.channel_name);
			}
		});
	}

	@Override
	protected void initData() {
		initMarqueeView();
		getList(false);
		getButtonConfig();
		getClickUrl();
	}


	private void initMarqueeView() {

		String city[] = {"北京", "天津", "济南", "南京", "广州", "大连", "长春", "黑龙江", "合肥", "成都", "重庆", "太原", "保定", "石家庄", "长沙", "武汉", "上海", "广州", "深圳", "广西"};
		String name[] = {"张先生", "李女士", "赵先生", "王先生", "赵女士", "汪先生", "蒋先生", "刘先生", "朱女士", "孙先生", "钱先生"};
		String num[] = {"10000", "8000", "15000", "12000", "5000", "20000", "18000", "6000"};
		String daikuan[] = {"小额贷款"};
		List<CharSequence> list = new ArrayList<>();
		for (int i = 0; i < 30; i++) {
			String numStr = num[new Random().nextInt(num.length)];
			String content = city[new Random().nextInt(city.length)] + "的" + name[new Random().nextInt(name.length)] + "申请的" + daikuan[new Random().nextInt(daikuan.length)] + numStr + "元已放款成功";
			SpannableString ss1 = new SpannableString(content);
			ss1.setSpan(new ForegroundColorSpan(Color.parseColor("#EE9300")), content.indexOf(numStr), content.indexOf(numStr) + numStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			list.add(ss1);
		}
		marqueeView.startWithList(list);
	}


	private void getList(final boolean isLoadMore) {

		BmobQuery query = new BmobQuery("list_config");
		query.order("createdAt");
//		query.addWhereEqualTo("list_id", "002");
		query.setSkip(count * 10);
		query.setLimit(10);
		//v3.5.0版本提供`findObjectsByTable`方法查询自定义表名的数据
		query.findObjectsByTable(new QueryListener<JSONArray>() {
			@Override
			public void done(JSONArray ary, BmobException e) {
				if (refreshLayout != null)
					refreshLayout.finishLoadmore();
				try {
					if (e == null) {
						String str = ary.toString();
						Log.e("XXX-list", str);
						if (isLoadMore) {
							if (JSON.parseArray(ary.toString(), ListConfig.class).size() == 0) {
								ToastHelper.toast("没有更多了");
								return;
							}
							adapter.add(JSON.parseArray(ary.toString(), ListConfig.class));
						} else {
							listConfigs = JSON.parseArray(ary.toString(), ListConfig.class);
							if (adapter == null) {
								adapter = new HomeListAdapter2(getActivity(), listConfigs);
								scrollViewWithListView.setAdapter(adapter);
							} else {
								adapter.update(listConfigs);
							}
						}

					} else {
//						ToastHelper.toast("获取数据失败");
					}
				} catch (Exception e2) {
//					ToastHelper.toast("获取数据失败");
				}
			}
		});

	}

	private void getButtonConfig() {

		BmobQuery query = new BmobQuery("type_info");
		query.order("createdAt");
		query.findObjectsByTable(new QueryListener<JSONArray>() {
			@Override
			public void done(JSONArray ary, BmobException e) {
				if (refreshLayout != null)
					refreshLayout.finishLoadmore();
				try {
					if (e == null) {
						String str = ary.toString();
						Log.e("XXX-button", str);
						buttonConfigBeens = JSON.parseArray(ary.toString(), ButtonConfigBean.class);
						if (homeGridViewAdapter == null) {
							homeGridViewAdapter = new HomeGridViewAdapter(getActivity(), buttonConfigBeens);
							gridView_8.setAdapter(homeGridViewAdapter);
						} else {
							homeGridViewAdapter.notifyDataSetChanged();
						}

					} else {
//						ToastHelper.toast("获取数据失败");
					}
				} catch (Exception e2) {
//					ToastHelper.toast("获取数据失败");
				}
			}
		});

	}

	ClickBean clickBean;

	private void getClickUrl() {

		BmobQuery query = new BmobQuery("top_baner");
		query.order("createdAt");
		query.findObjectsByTable(new QueryListener<JSONArray>() {
			@Override
			public void done(JSONArray ary, BmobException e) {
				if (refreshLayout != null)
					refreshLayout.finishLoadmore();
				try {
					if (e == null) {
						String str = ary.toString();
						Log.e("XXX-top_baner", str);
						List<ClickBean> clickBeens = JSON.parseArray(str, ClickBean.class);
						if (clickBeens != null || clickBeens.size() > 0) {
							clickBean = clickBeens.get(0);
						}
					} else {
//						ToastHelper.toast("获取数据失败");
					}
				} catch (Exception e2) {
//					ToastHelper.toast("获取数据失败");
				}
			}
		});
	}


	@OnClick(R.id.topButton)
	public void topButton() {
		if (clickBean == null)
			return;
		WebViewActivity.skip(getActivity(), clickBean.getTop_button(), "试试我能借多少");
	}

	@OnClick(R.id.topBanner)
	public void topBanner() {
		if (clickBean == null)
			return;
		WebViewActivity.skip(getActivity(), clickBean.getBanner_go(), "借贷");
	}

	@OnClick(R.id.tvXinyongDengji)
	public void tvXinyongDengji() {
		if (clickBean == null)
			return;
		WebViewActivity.skip(getActivity(), clickBean.getTop_lineurl(), "信用等级");
	}

	@Bind(R.id.frHuodong)
	FrameLayout frHuodong;

	@OnClick(R.id.close)
	public void close() {
		frHuodong.setVisibility(View.GONE);
	}

	@OnClick(R.id.frHuodong)
	public void frHuodong() {
		startActivity(QiangqianActivity.class);
	}

}
